package it.patamau.persistence;

import it.patamau.bukkit.deathmatch.DMPlayerStat;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

/**
 * Generic serialization
 * @author Matteo
 *
 * @param <T>
 */
public class Serializer<T> {
	
	private String filename;
	
	public Serializer(String filename){
		this.filename = filename;
	}

	public void store(T object) throws IOException{
		FileOutputStream	fos = new FileOutputStream(filename);
		ObjectOutputStream	out = new ObjectOutputStream(fos);
		out.writeObject(object);
		out.close();
	}
	
	@SuppressWarnings("unchecked")
	public T load() throws IOException, ClassNotFoundException{
		FileInputStream	fis = new FileInputStream(filename);
		ObjectInputStream in = new ObjectInputStream(fis);
		T object = (T)in.readObject();
		in.close();
		return object;
	}
	
	/**
	 * Testing
	 * @param args
	 */
	public static void main(String args[]){
		Serializer<ArrayList<String>> fm = new Serializer<ArrayList<String>>("strings.txt");
		ArrayList<String> strings = new ArrayList<String>();
		try {
			strings = fm.load();
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		}
		for(String s: strings){
			System.out.println(s);
		}
		strings.clear();
		
		strings.add("hello");
		strings.add("how");
		strings.add("are");
		strings.add("you");
		strings.add("?");
		try {
			fm.store(strings);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		Serializer<ArrayList<DMPlayerStat>> fmp = new Serializer<ArrayList<DMPlayerStat>>("players.dat");
		ArrayList<DMPlayerStat> players = new ArrayList<DMPlayerStat>();
		try {
			players = fmp.load();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}	
		
		for(DMPlayerStat p: players){
			System.out.println(p);
		}
		
		players.clear();
		players.add(new DMPlayerStat("goofy"));
		players.add(new DMPlayerStat("donald"));
		players.add(new DMPlayerStat("mickey"));
		
		try {
			fmp.store(players);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
